package com.itany.shop.tran.impl;

import com.itany.shop.exception.ServiceException;
import com.itany.shop.tran.TransactionManager;
import com.itany.shop.util.JDBCUtil;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Author:石小俊
 * @Date:2022/11/15 14:10
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
public class TransactionManagerImpl implements TransactionManager {
    @Override
    public void begin() {
        try {
            JDBCUtil.getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ServiceException("开启事务失败");
        }
    }

    @Override
    public void commit() {
        try {
            Connection conn = JDBCUtil.getConnection();
            // 如果当前事务是手动事务
            if(!conn.getAutoCommit()){
                // 手动提交事务
                conn.commit();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ServiceException("事务提交失败");
        } finally {
            // 事务结束后释放连接
            JDBCUtil.close();
        }
    }

    @Override
    public void rollback() {
        try {
            Connection conn = JDBCUtil.getConnection();
            // 如果当前事务是手动事务
            if(!conn.getAutoCommit()){
                // 手动回滚事务
                conn.rollback();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new ServiceException("事务回滚失败");
        } finally {
            JDBCUtil.close();
        }
    }
}
